package com.litong.litongjiaoyu.controller;

import com.alibaba.fastjson.JSONObject;
import com.litong.litongjiaoyu.annotation.IgnoreAuth;
import com.litong.litongjiaoyu.entity.StudentLeave;
import com.litong.litongjiaoyu.entity.WxMaTemplateData;
import com.litong.litongjiaoyu.entity.WxMssVo;
import com.litong.litongjiaoyu.service.CommenService;
import com.litong.litongjiaoyu.service.LeaveService;
import com.litong.litongjiaoyu.service.PositionService;
import com.litong.litongjiaoyu.service.StudentService;
import com.litong.litongjiaoyu.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName LeaveController
 * @Description 学生考勤系统控制层
 * @Author jingz
 * @Date 2019/11/25 10:42
 * @Version 1.0
 **/
@RestController
@RequestMapping("/leave")
public class LeaveController {
    /**
     * 门面模式日志输出
     */
    private Logger LOGGER = LoggerFactory.getLogger(LeaveController.class);

    /**
     * 引入职位服务层
     */
    @Resource
    private PositionService positionService;

    @Autowired
    private LeaveService leaveService;
    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;

    @Autowired
    private StudentService studentService;
    @Autowired
    private CommenService commenService;


    /**
     * 获取指定班级和校区查询请假的学生
     *
     * @param jsonObject 其中包含班级和校区信息
     * @return
     */
    @IgnoreAuth
    @ResponseBody
    @PostMapping("/query")
    public JSONResult query (@RequestBody JSONObject jsonObject) {
        LOGGER.info("获取指定班级和校区查询请假的学生");


        return JSONResult.ok(leaveService.query(jsonObject.getString("campus")));
    }
    
    /**
     * 家长端获取请假记录
     * @param jsonObject
     * @return
     */
    @ResponseBody
    @PostMapping("/getyourselfleave")
    public JSONResult getYourSelf(@RequestBody JSONObject jsonObject) {
        List<StudentLeave> studentLeaves = leaveService.getYourselfLeave(jsonObject.getString("phone"));
        
        if (studentLeaves.size() > 0) {
            return JSONResult.ok(studentLeaves);
        } else {
            return JSONResult.ok(null);
        }
    }
    
    /**
     * 获取学生考勤基本信息
     * @param jsonObject 校区和班级
     * @return
     */
    @IgnoreAuth
    @ResponseBody
    @PostMapping("/select")
    public JSONObject select (@RequestBody JSONObject jsonObject) {
        LOGGER.info("获取学生考勤所需信息");

        String className = jsonObject.getString("classname"),
                campus = jsonObject.getString("campus");

        JSONObject jsonObject1 = new JSONObject();

        jsonObject1.put("noLeave",leaveService.getStudentList(className, campus));
        jsonObject1.put("leave", leaveService.getLeaveStudent(className, campus));

        return jsonObject1;
    }


    /**
     * 学生发送给老师
     *
     * @param jsonObject 请微信小程序接收到的学生请假信息
     * @return 是否成功
     */
    @IgnoreAuth
    @ResponseBody
    @PostMapping("/application")
    public JSONResult add (@RequestBody JSONObject jsonObject) {
        StudentLeave studentLeave = jsonObject.getObject("userinfo", StudentLeave.class);
        String campus = jsonObject.getString("campus");

        //日期格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");


        Map<String, WxMaTemplateData> data = new HashMap<String, WxMaTemplateData>(3);

        //学生姓名
        WxMaTemplateData wxMaTemplateData1 = new WxMaTemplateData();
        wxMaTemplateData1.setValue(studentService.selectByPhone(studentLeave.getPhone()));
        data.put("name1", wxMaTemplateData1);

        //请假开始日期
        WxMaTemplateData wxMaTemplateData2 = new WxMaTemplateData();
        wxMaTemplateData2.setValue(simpleDateFormat.format(studentLeave.getStartdate()));
        data.put("date3", wxMaTemplateData2);

        //请假结束日期
        WxMaTemplateData wxMaTemplateData3 = new WxMaTemplateData();
        wxMaTemplateData3.setValue(simpleDateFormat.format(studentLeave.getEnddate()));
        data.put("date4", wxMaTemplateData3);

        WxMssVo wxMssVo = null;


        List<String> openids = positionService.getOpenId("学生请假");

        for (String openid : openids) {
            wxMssVo = new WxMssVo();
            //设置接收人openid
            wxMssVo.setTouser(openid);
            wxMssVo.setTemplate_id("FjWr_c6N2UtcqVYgbHPcBVuTLr83EN5UjFg-7gmTkOs");
            wxMssVo.setPage("pages/leave/leave");
            wxMssVo.setData(data);

            //获取消息发送结果
            sendMessage(wxMssVo,"wx6a41faf108b8ecab", "6e9c02ef2d83dcd91a2f0e730a9aa358");
        }

        if (leaveService.application(studentLeave) > 0) {
            return JSONResult.ok();
        } else {
            return JSONResult.errorMsg("fail");
        }
    }

    /**
     * 老师发给学生
     *
     * @param jsonObject 所需信息
     * @return
     */
    @ResponseBody
    @PostMapping("/review")
    public JSONResult review (@RequestBody JSONObject jsonObject) {
        StudentLeave studentLeave = jsonObject.getObject("leave", StudentLeave.class);

        Map<String, WxMaTemplateData> data = new HashMap<String, WxMaTemplateData>(3);

        //学生姓名
        WxMaTemplateData wxMaTemplateData1 = new WxMaTemplateData();
        wxMaTemplateData1.setValue(studentLeave.getName());
        data.put("name1", wxMaTemplateData1);

        //请假状态
        WxMaTemplateData wxMaTemplateData2 = new WxMaTemplateData();
        wxMaTemplateData2.setValue(studentLeave.getStatus());
        data.put("phrase1", wxMaTemplateData2);

        //发送
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(commenService.getOpenId(studentLeave.getPhone()));
        wxMssVo.setTemplate_id("w3XM3X5VzHD_6eeevDgFEpb7o3TxU8cwU5RLZR3KsiI");
        wxMssVo.setPage("pages/index/index");
        wxMssVo.setData(data);

        // 获取消息发送结果
        // 理通教育家长端appid和appsecret
        sendMessage(wxMssVo,
                "wx78763b2bea2646c2",
                "571a3836b6b557d2e7dc1aaeabdc0be2"
        );

        // 判断是否发送成功，如果发送成功保存至数据库
        // 若没有，返回错误信息
        if (leaveService.updateStatus(studentLeave) > 0) {
            return JSONResult.ok();
        } else {
            return JSONResult.errorMsg("fail");
        }
    }


    /**
     * 多线程发送微信订阅消息
     *
     * @param wxMssVo
     */
    @Async
    public synchronized void sendMessage (WxMssVo wxMssVo, String appid, String appSecret) {
        JSONObject result = wxPushServiceQcl.pushOneUser(appid, appSecret, wxMssVo);
    }
}
